package com.hqyj.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.hqyj.config.MyBatisPlusPageConfig;
import com.hqyj.dao.MenuMapper;
import com.hqyj.dao.OrderMapper;
import com.hqyj.dao.SetMealMapper;
import com.hqyj.dao.UserMapper;
import com.hqyj.entity.*;
import com.hqyj.service.IOrderService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.concurrent.TimeUnit;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author rock
 * @since 2022-09-20
 */
@Service
public class OrderServiceImpl extends ServiceImpl<OrderMapper, Order> implements IOrderService {
    //导入dao层
    @Resource
    OrderMapper orderMapper;
    @Resource
    UserMapper userMapper;
    @Resource
    MenuMapper menuMapper;
    @Resource
    SetMealMapper setMealMapper;
    //导入分页配置
    @Autowired
    MyBatisPlusPageConfig myBatisPlusPageConfig;

    //导入redis缓存
    @Autowired
    RedisTemplate<String,Object> redisTemplate;


    /**
     * 分页查询所以订单信息
     * @param order
     * @return
     */
    @Override
    public ResultVo queryAllOrder(Order order) {
        ResultVo rv = new ResultVo();
        //参创建分页对象
        Page<Order> page = new Page<>(order.getPage(),order.getRow());
        //查询分页
        QueryWrapper<Order> queryWrapper = new QueryWrapper<>();
        //根据用户id的模糊查询
        queryWrapper.like(order.getUid() != null && !order.getUid().equals(""),
                "uid",
                order.getUid());

        //根据菜品名称的模糊查询
        queryWrapper.like(order.getDishName() != null && !order.getDishName().equals(""),
                "dish_name",
                order.getDishName());
        //根据套餐名称的模糊查询
        queryWrapper.like(order.getMealsName() != null && !order.getMealsName().equals(""),
                "meals_name",
                order.getMealsName());

        queryWrapper.orderByAsc("create_time");
        Page<Order> orderPage = orderMapper.selectPage(page, queryWrapper);

       //判断是否有结果
        if (orderPage.getRecords().size() > 0){
            //记录分页数据
            Map<String,Object> map = new HashMap<>();
            //当前页面集合
            map.put("list",orderPage.getRecords());
            //总的数据条数
            map.put("total",orderPage.getTotal());
            //总的页数
            map.put("totoalPage",orderPage.getPages());

            rv.setSuccess(true);
            rv.setData(map);
        }else {
            rv.setSuccess(false);
            rv.setInfo("查询失败");
        }




        return rv;
    }

    /**
     * 根据用户查询订单
     * @param order
     * @return
     */
    @Override
    public ResultVo queryOrderByUser(Order order) {
        ResultVo rv = new ResultVo();
        //参创建分页对象
        Page<Order> page = new Page<>(order.getPage(),order.getRow());
        //根据用户账户得到用户id
        QueryWrapper<User> userQueryWrapper = new QueryWrapper<>();
        userQueryWrapper.eq("account",order.getAccount());
        User user = userMapper.selectOne(userQueryWrapper);
        //查询分页
        QueryWrapper<Order> queryWrapper = new QueryWrapper<>();
        //根据用户id的模糊查询
        queryWrapper.like(
                "uid",
                user.getUid());

        //根据菜品名称的模糊查询
        queryWrapper.like(order.getDishName() != null && !order.getDishName().equals(""),
                "dish_name",
                order.getDishName());
        //根据套餐名称的模糊查询
        queryWrapper.like(order.getMealsName() != null && !order.getMealsName().equals(""),
                "meals_name",
                order.getMealsName());

        queryWrapper.orderByAsc("create_time");
        Page<Order> orderPage = orderMapper.selectPage(page, queryWrapper);

        //判断是否有结果
        if (orderPage.getRecords().size() > 0){
            //记录分页数据
            Map<String,Object> map = new HashMap<>();
            //当前页面集合
            map.put("list",orderPage.getRecords());
            //总的数据条数
            map.put("total",orderPage.getTotal());
            //总的页数
            map.put("totoalPage",orderPage.getPages());

            rv.setSuccess(true);
            rv.setData(map);
        }else {
            rv.setSuccess(false);
            rv.setInfo("查询失败");
        }




        return rv;
    }

    /**
     * 根据地址查询订单（为外卖员准备的）
     * @param address
     * @return
     */
    @Override
    public ResultVo queryOrderByAddress(String address) {
        ResultVo rv = new ResultVo();

        return rv;
    }

    /**
     * 查询订单的详细信息
     * @param oid
     * @return
     */
    @Override
    public ResultVo showOrder(int oid) {
        //定义key
        String key = "exam:" + oid;
        //判断缓存中是否有数据
        Object obj = redisTemplate.opsForValue(). get(key);
        Order order = new Order();
        if (obj == null){
            //订单queryWrapper对象
            QueryWrapper<Order> queryWrapper = new QueryWrapper<>();
            //填入订单编号
            queryWrapper.eq("oid",oid);
            //根据oid查询订单
            Order one = orderMapper.selectOne(queryWrapper);
             order.setUid(one.getUid());
             order.setCreateTime(one.getCreateTime());
             order.setOid(oid);

            if (!one.getDishName().equals("") && !one.getMealsName().equals("")) {
                //如果该订单的菜品与套餐都有

                //获取菜品的数组
                String[] dishNames = one.getDishName().split(",");
                //获取套餐的数组
                String[] mealsNames = one.getMealsName().split(",");
                //创建菜品的queryWrapper对象
                QueryWrapper<Menu> menuQueryWrapper = new QueryWrapper<>();
                //创建套餐的queryWrapper对象
                QueryWrapper<SetMeal> setMealQueryWrapper = new QueryWrapper<>();
                //调用in方法
                menuQueryWrapper.in("dish_name",dishNames);
                //获取菜品集合
                List<Menu> menuList = menuMapper.selectList(menuQueryWrapper);
                //调用in方法
                setMealQueryWrapper.in("meals_name",mealsNames);
                //获取套餐集合
                List<SetMeal> setMealList = setMealMapper.selectList(setMealQueryWrapper);

                //将菜品集合添加进订单中的菜品集合
                order.setMenusList(menuList);
                //将套餐集合添加进订单中的套餐集合
                order.setSetMealList(setMealList);
                System.out.println(order);
            }else if (!one.getDishName().equals("") && one.getMealsName().equals("")){
                //如果只有菜品没有套餐
                //获取菜品的数组
                String[] dishNames = one.getDishName().split(",");
                //创建菜品的queryWrapper对象
                QueryWrapper<Menu> menuQueryWrapper = new QueryWrapper<>();
                //调用in方法
                menuQueryWrapper.in("dish_name",dishNames);
                //获取菜品集合
                List<Menu> menuList = menuMapper.selectList(menuQueryWrapper);
                //将菜品集合添加进订单中的菜品集合
                order.setMenusList(menuList);
                System.out.println(order);

            }else if(one.getDishName().equals("") && !one.getMealsName().equals("")){
                //如果只有套餐没有菜品
                //获取套餐的数组
                String[] mealsNames = one.getMealsName().split(",");
                //创建套餐的queryWrapper对象
                QueryWrapper<SetMeal> setMealQueryWrapper = new QueryWrapper<>();
                //调用in方法
                setMealQueryWrapper.in("meals_name",mealsNames);
                //获取套餐集合
                List<SetMeal> setMealList = setMealMapper.selectList(setMealQueryWrapper);
                //将套餐集合添加进订单中的套餐集合
                order.setSetMealList(setMealList);
                System.out.println(order);
            }
            //存入缓存
//            redisTemplate.opsForValue().set(key,order,1, TimeUnit.HOURS);

        }else {
            //缓存中取数据
            order =(Order) obj;
        }


        ResultVo rv = new ResultVo();
        if (order != null){
            rv.setSuccess(true);
            rv.setData(order);
        }else {
            rv.setInfo("查询失败");
        }
        return rv;
    }

    /**
     * 添加订单
     * @param order
     * @return
     */
    @Override
    public ResultVo addOrder(Order order) {
        ResultVo rv = new ResultVo();
        if (order.getDishName().equals("") && order.getMealsName().equals("")){
            rv.setSuccess(false);
            rv.setInfo("您还未点餐，是没有菜品符合您的口味吗？");
        }else {
            //获取系统当前时间，并将Java时间转换为数据库的时间格式
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss");
            //存入时间
            order.setCreateTime(sdf.format(new Date()));
//        order.setCreateTime(null);
            int num = orderMapper.insert(order);
            if (num > 0) {
                rv.setSuccess(true);
                rv.setInfo("下单成功");
            } else {
                rv.setSuccess(false);
                rv.setInfo("添加失败");
            }
        }

        return rv;
    }

    /**
     * 修改订单
     * @param order
     * @return
     */
    @Override
    public ResultVo updateOrder(Order order) {
        ResultVo rv = new ResultVo();
        //获取系统当前时间,并设置时间格式
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss");
        //将时间存入
        order.setCreateTime(sdf.format(new Date()));

        int num = orderMapper.updateById(order);
        if (num > 0){
            rv.setSuccess(true);

        }else {
            rv.setSuccess(false);
            rv.setInfo("修改失败");
        }
        return rv;
    }

    /**
     * 删除订单
     * @param oid
     * @return
     */
    @Override
    public ResultVo delOrderByOid(int oid) {
        ResultVo rv = new ResultVo();

        QueryWrapper<Order> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("oid",oid);
        int num = orderMapper.delete(queryWrapper);
        if (num > 0){
            rv.setSuccess(true);
            rv.setInfo("删除成功");
        }else {
            rv.setInfo("删除失败");
        }


        return rv;
    }

    /**
     *计算订单总价
     * @param order
     * @return
     */
    @Override
    public ResultVo totalOrder(Order order) {
       ResultVo rv = new ResultVo();
        //定义key
        String key = "exam:" + order.getOid();
        //从缓存中取出订单信息
        Order o = (Order) redisTemplate.opsForValue().get(key);
        //建立菜品、套餐的价格的集合
        List<Menu> menuList = new LinkedList<>();
        List<SetMeal> setMealList = new LinkedList<>();

        if (o.getMenusList() != null){
           for (Menu m : o.getMenusList()){
                menuList.add(m);
           }
        }
        if (o.getSetMealList() != null){
            for (SetMeal sm : o.getSetMealList()) {
                setMealList.add(sm);
            }
        }

        //把价格转换成数组类型
        String[] menuArr = order.getMt().split(",");
        String[] setMealArr = order.getSt().split(",");


        //计算总价
        int total = 0;
        //统计菜品价格
        if (menuList != null) {
            for (int i = 0; i < menuList.size(); i++) {
                if ((menuList.get(i).getMid() + "").equals(menuArr[i])) {
                    int price = menuList.get(i).getMenuPrice();
                    total = total + price;
                }
            }
        }
        //统计套餐价格
        if (setMealList != null){
            for (int i = 0; i < setMealList.size(); i++) {
                if ((setMealList.get(i).getMsid() + "").equals(setMealArr[i])) {
                    int price = setMealList.get(i).getSmPrice();
                    total = total + price;
                }
            }
        }

        //创建一个新的订单
        Order order1 = new Order();
        //根据订单编号修改订单订单总价
        order1.setOid(order.getOid());
        order1.setTotal(total + "");
        orderMapper.updateById(order1);
        //返回结果集
        rv.setSuccess(true);
        System.out.println("====total:" + total);
        rv.setData(total);


       return rv;
    }
}
